package com.yuzhitong.shapi.presenter;

import android.os.Handler;
import android.os.Looper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import a.a.a.MyApplication;
import com.yuzhitong.shapi.base.BasePresenter;
import com.yuzhitong.shapi.base.net.BaseListBean;
import com.yuzhitong.shapi.base.net.BaseObjectBean;
import com.yuzhitong.shapi.bean.MovieBean;
import com.yuzhitong.shapi.bean.PlayListBean;
import com.yuzhitong.shapi.contract.PlayContract;
import com.yuzhitong.shapi.model.PlayModel;
import com.yuzhitong.shapi.net.MyObserver;
import com.yuzhitong.shapi.net.RxScheduler;

import java.io.IOException;
import java.util.Map;

import io.reactivex.rxjava3.annotations.NonNull;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Brsya
 * CreateDate: 2022/5/28  11:38
 * Description:
 * 播放播放
 */
public class PlayPresenter extends BasePresenter<PlayContract.View> implements PlayContract.Presenter {
    private PlayContract.Model model;

    public PlayPresenter() {
        model = new PlayModel();
    }

    @Override
    public void getHot(int id) {
        mView.showLoading();

        Map<String, Object> par = getPublicPar();
        par.put("id", id);

        model.getHot(par)
                .compose(RxScheduler.Obs_io_main())
                .to(mView.bindAutoDispose())
                .subscribe(new MyObserver<BaseObjectBean<PlayListBean>>(mView) {
                    @Override
                    public void complete(BaseObjectBean<PlayListBean> baseBean) {
                    }

                    @Override
                    public void success(@NonNull BaseObjectBean<PlayListBean> baseBean) {
                        baseBean.handleData(PlayListBean.class);
                        if (baseBean.getData() != null) {
                            if (baseBean.getData().getPlayerList() == null || baseBean.getData().getPlayerList().size() == 0) {
                                mView.goDetail();
                                return;
                            }
                            mView.playListSuccess(baseBean.getData());
                        }
                    }

                });

    }

    @Override
    public void getPlayAddress(String infoUrl) {

        mView.showLoading();

        Map<String, Object> par = getPublicPar();
        par.put("infoUrl", infoUrl);

        model.getPlayAddress(par)
                .compose(RxScheduler.Obs_io_main())
                .to(mView.bindAutoDispose())
                .subscribe(new MyObserver<BaseObjectBean<String>>(mView) {
                    @Override
                    public void success(@NonNull BaseObjectBean<String> baseBean) {
                        baseBean.handleData(String.class);
                        if (baseBean.getData() != null) {
                            mView.getPlayAddress(baseBean.getData());
                        }
                    }
                });
    }

    @Override
    public void getLike(int id, String tag) {
        if (model == null) {
            return;
        }

        if (mView == null) {
            return;
        }

        Map<String, Object> par = getPublicPar();
        par.put("videoId", id);
        par.put("tag", tag);

        model.getLike(par)
                .compose(RxScheduler.Obs_io_main())
                .to(mView.bindAutoDispose())
                .subscribe(new MyObserver<BaseListBean<MovieBean>>(mView) {
                    @Override
                    public void complete(BaseListBean<MovieBean> baseBean) {
                    }
                    @Override
                    public void success(@NonNull BaseListBean<MovieBean> baseBean) {
                        baseBean.handleData(MovieBean.class);
                        if (mView != null) {
                            if (baseBean.getData() != null && baseBean.getData().size() > 0) {
                                mView.showDayHot(baseBean.getData());
                            }else{
                                mView.showNoMore();
                            }
                        }
                    }
                });
    }

    @Override
    public void getPlayAddressNew(String infoUrl, String type, Map<String, String> par) {
        if (mView == null) {
            return;
        }
        mView.showLoading();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request;
        if ("get".equalsIgnoreCase(type)) {
            StringBuffer sb = new StringBuffer();
            sb.append(infoUrl);
            sb.append("?");

            for (String s : par.keySet()) {
                sb.append(s)
                        .append(par.get(s))
                .append("&");
            }

            sb.delete(sb.length() - 1, sb.length());

            request = new Request.Builder()
                    .get()
                    .url(sb.toString())
                    .build();
        }else{
            FormBody.Builder builder = new FormBody.Builder();


            for (String s : par.keySet()) {
                builder.add(s, par.get(s));
            }
            FormBody formBody = builder.build();

            request = new Request.Builder()
                    .url(infoUrl)
                    .post(formBody)
                    .build();
        }
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                if (body == null) {
                    return;
                }
                final String res = body.string();
            }
        });
    }

    @Override
    public void getPlayAddressNew(String infoUrl, String type, String url) {
        mView.showLoading();
        OkHttpClient okHttpClient = new OkHttpClient();
        if (!"get".equalsIgnoreCase(type)) {
            return;
        }

        Request request = new Request.Builder()
                .get()
                .url(infoUrl + url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                if (body == null) {
                    return;
                }
                final String res = body.string();
                JSONObject jsonObject = JSON.parseObject(res);
                String path = MyApplication.playAddressBean.getPath();
                String[] split = path.split("\\.");
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {

                        JSONObject temp = jsonObject;
                        for (int i = 0; i < split.length; i++) {
                            if (i == split.length - 1) {
                                if (mView == null) {
                                    return;
                                }
                                mView.getPlayAddress(temp.getString(split[i]));
                                mView.hideLoading();
                                return;
                            }
                            temp = temp.getJSONObject(split[i]);
                        }
                        if (mView == null) {
                            return;
                        }
                        mView.hideLoading();
                        mView.getPlayAddressError();
                    }
                });
            }
        });
    }
}
